package servlet;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import service.HelloService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/sayHello")
public class HelloServlet extends HttpServlet {
    //错
//    private  ApplicationContext ac;
//
//    @Override
//    public void init() throws ServletException {
//       ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("HelloServlet.service()");

        String name=request.getParameter("name");

        //错
//        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");


//        ApplicationContext ac= (ApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

        ApplicationContext ac= WebApplicationContextUtils.getWebApplicationContext(getServletContext());

        System.out.println("ac = " + ac);

        HelloService helloService=ac.getBean(HelloService.class);

        String message=helloService.sayHello(name);

        request.setAttribute("message",message);

        request.getRequestDispatcher("/hello.jsp").forward(request,response);


    }
}
